package org.zk.dubbo_consumer.controller;



import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zk.dubbo_consumer.util.DESUtil;
import org.zk.dubbo_consumer.util.PhoneOrMail;
import org.zk.entity.Course;
import org.zk.entity.Teacher;
import org.zk.entity.TeacherBill;
import org.zk.service.*;
import org.zk.entity.TeacherBill;
import org.zk.entity.User;
import org.zk.service.CourseService;
import org.zk.service.OrderService;
import org.zk.service.TeacherService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Alicelonely
 * @since 2019-12-11
 */
@Controller
public class TeacherController {
    @Resource
    @Getter
    @Setter
    private TeacherService teacherService;

    @Resource
    @Getter
    @Setter
    private OrderService orderService;

    @Resource
    @Getter
    @Setter
    private CourseService courseService;
    @Resource
    @Getter
    @Setter
    private AdminBillService adminBillService;

    public TeacherService getTeacherService() {
        return teacherService;
    }


    /**
     * 采用DES加密用户登录   （高顺）
     *
     * @param password
     * @param gphone
     * @param request
     * @return
     */
    @RequestMapping("/teacherPhoneLoginDes")
    @ResponseBody
    public Map phoneLoginDes(String password, String gphone, HttpServletRequest request,Model model) {
        Map map=new HashMap();
        HttpSession session = request.getSession(true);   //用HTTPSession需写这句
        boolean result = PhoneOrMail.isPhoneOrMail(gphone);
//        String jmphone = DESUtil.encryptBasedDes(gphone);    //加密后的邮箱或手机号
//        String jmPwd = DESUtil.encryptBasedDes(password);      //加密后的密码
        Teacher teacher = null;
           try{
               UsernamePasswordToken token = new UsernamePasswordToken(gphone,password);
               Subject subject = SecurityUtils.getSubject();
               subject.login(token);
               teacher = (Teacher) subject.getPrincipal();
           } catch (Exception e){
               if (e.equals("NullPointerException")){
                   map.put("msg","该用户不是讲师用户!");
               }
           }

        try {
            if (teacher != null) {
                session.setAttribute("teacher", teacher);
                map.put("teacher", teacher);
                String pp = teacher.getTeacherPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                session.setAttribute("pp", pp);
                map.put("msg","ok");
            } else {
                map.put("msg", "该用户不是讲师用户！");
            }
        }catch (NullPointerException n){
            map.put("msg","该用户不是讲师用户!");
        }

        return map;
    }

    @RequestMapping("/teacherIndex2")
    public ModelAndView teacherIndex2(){
        return new ModelAndView("indexTwo.html");
    }

@RequestMapping("/toWallet")
    public ModelAndView toWallet(int id) {
    ModelAndView mv = new ModelAndView("teacher/wallet");
    Teacher teacher = teacherService.getTeacherById(id);
    mv.addObject("teacher", teacher);
    return mv;
}
    /**
     * LYT 教师详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/tixianMessage/{id}")
    public ModelAndView toTixianMessage(@PathVariable("id") int id, Model model) {
        Teacher teacher = teacherService.getTeacherById(id); /*根据教师id得到教师详情*/
        model.addAttribute("teacher", teacher);
        return new ModelAndView("admin/tixianMessage");
    }

    /**
     * LYT  平台提现
     *
     * @param id
     * @param teacher
     * @return
     */
    @RequestMapping("/toTixianMessage")
    @ResponseBody
    public int toTeacherMessage(int id, Teacher teacher) {
        Teacher t = teacherService.getTeacherById(id);/*根据老师id查找提现详情*/
        /*判断教师输入的数据是否与提现详情一致*/
        if (teacher.getTeacherMoney() > t.getTeacherMoney() || teacher.getTeacherMoney() <= 0) {
            return 2;
        } else if (!teacher.getTeacherTxpwd().equals(t.getTeacherTxpwd()) || teacher.getTeacherTxpwd() == null) {
            return 3;
        } else {
            Map map = new HashMap();
            map.put("id", id);
            map.put("teacher", teacher);
            teacherService.updateTeacherMoney(map); /*提现成功后改变教师钱包余额*/
            teacherService.insertTixianTeacher(map); /*在教师转账记录中加入一条提现记录*/
            int teacherBillId = teacherService.getTeacherBillById(id);
            map.put("teacherBillId", teacherBillId);
            teacherService.insertTixian(map); /*在提现表中插入一条未处理的提现申请*/
            return 0;
        }
    }

    /**
     * 判断教师是否绑定支付宝
     * @param id
     * @param model
     * @return
     */

    @RequestMapping("/addZhifubao/{id}")
    @ResponseBody
    public ModelAndView addZhifubbao(@PathVariable("id") int id, Model model) {
        model.addAttribute("id", id);
        Teacher teacher = teacherService.getTeacherById(id);
        model.addAttribute("teacherZhifubao", teacher.getTeacherZhifubao());
        return new ModelAndView("admin/addZhifubaoMessage");


    }

    /**LYT
     * 教师绑定或更新支付宝账号
     * @param id
     * @param teacherZhifubao
     * @param teacherTxpwd
     * @return
     */
    @RequestMapping("addTeacherZhifubao")
    @ResponseBody
    public String addTZhifubao(int id,String teacherZhifubao,String teacherTxpwd){
        Map map=new HashMap();
        if(teacherZhifubao.equals("")||teacherTxpwd.equals("")){
            return "0";
        }
        map.put("id", id);
        map.put("teacherZhifubao", teacherZhifubao);
        map.put("teacherTxpwd", teacherTxpwd);
        teacherService.insertTeacherZhifubao(map);
        return "1";
    }



    /**
     * 教师个人中心（我的课程）
     *
     * @param
     */
    @RequestMapping("/toKeCheng")
    public ModelAndView toKeCheng() {
        ModelAndView modelAndView = new ModelAndView("teacher/kecheng");
        return modelAndView;
    }

    /**
     * 根据教师id和审核状态查询课程
     *
     * @param courseFlag
     * @param session
     * @return
     */
    @RequestMapping("/getCouList")
    @ResponseBody
    public List getCourseList(int courseFlag, HttpSession session) {
        String flag;
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        if (courseFlag == -1) {
            flag = "";
        } else {
            flag = String.valueOf(courseFlag);
        }
        Map map = new HashMap();
        map.put("courseFlag", flag);
        map.put("teacherId", teacher.getTeacherId());
        /*map.put("teacherId",teacher.getTeacherId());*/
        List<Course> list = courseService.getCourseByTidAndFlag(map);
        for (Course cou : list) {
            String courseCover = cou.getCourseCover();
            String path = "/static/image/picture/" + courseCover;
            cou.setCourseCover(path);
            String a = cou.getCourseFlag();
            if (a.equals("0")) {
                cou.setCourseFlag("未审核");
            }
            if (a.equals("1")) {
                cou.setCourseFlag("已上线");
            }
            if (a.equals("2")) {
                cou.setCourseFlag("已拒绝");
            }
        }
        return list;
    }

    /**
     * to教师个人信息页
     *
     * @param
     */
    @RequestMapping("/toInfo")
    public ModelAndView toInfo(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("teacher/information");
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        Teacher teacher1 = teacherService.getTeacherById(teacher.getTeacherId());
        if (teacher1.getTeacherSex().equals("0")) {
            teacher1.setTeacherSex("男");
        } else {
            teacher1.setTeacherSex("女");
        }
        if (teacher1.getTeacherPic() != null) {
            String a = teacher1.getTeacherPic();
            String path = "/static/image/picture/" + a;
            teacher1.setTeacherPic(path);
        }
        teacher1.setTeacherPhone(DESUtil.decryptBasedDes(teacher1.getTeacherPhone()));
        modelAndView.addObject("teacher", teacher1);
        return modelAndView;
    }

    /**
     * 教师基本信息修改
     *
     * @param
     */
    @ResponseBody
    @RequestMapping("/editMsg")
    public List updateTeacher(Teacher teacher, HttpSession session) {
        List<String> ls = new ArrayList<>();
        Teacher teacher1 = (Teacher) session.getAttribute("teacher");
        int teacherId = teacher1.getTeacherId();
        teacher.setTeacherId(teacherId);
        int result = teacherService.updatetoTeacher(teacher);
        if (result > 0) {
            ls.add("success");
        } else {
            ls.add("fail");
        }
        return ls;
    }

    /**
     * 修改头像
     *
     * @param
     */
    @ResponseBody
    @RequestMapping("/editPic")
    public List editPic(@RequestParam("file") MultipartFile file, HttpSession session) {
        List list = new ArrayList();
        Teacher teacher= (Teacher) session.getAttribute("teacher");
        int teacherId=teacher.getTeacherId();
        String fileName = file.getOriginalFilename();  // 文件名
        if (!"".equals(fileName)) {
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            File fileMkdir = new File("E:\\teacherPic");
            if (!fileMkdir.exists()) {
                fileMkdir.mkdir();
            }
            String filePath = fileMkdir.getPath() + "\\";
            fileName = UUID.randomUUID() + suffixName;  //新文件名
            File dest = new File(filePath + fileName);
            try {
                //写入文件
                file.transferTo(dest);
            } catch (IOException e) {
            }
        }
        Teacher teacher1 = new Teacher();
        teacher1.setTeacherId(teacherId);
        teacher1.setTeacherPic(fileName);
        int reault = teacherService.updatePic(teacher1);
        return list;
    }

    /**
     * 进入教师收入明细页面
     *
     * @param
     */
    @RequestMapping("/toShouRu")
    public ModelAndView toShouRu() {
        /*Map map = new HashMap();
        map.put("start", "2019-01-01");
        map.put("end", "2020-01-01");
        map.put("teacherId", 1);
        List<Map> ls = orderService.queryShouRu(map);
        for (Map m:ls) {
            System.out.println(m.get("countVip"));
        }*/
        return new ModelAndView("teacher/shouru");
    }

    @RequestMapping("/getShouRu")
    @ResponseBody
    public List getShouRu(HttpSession session, String start, String end) {
        Teacher teacher= (Teacher) session.getAttribute("teacher");
        Map map = new HashMap();
        map.put("teacherId", teacher.getTeacherId());
        String a;
        String b;
        if (start.equals("") && end.equals("")) {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR); //当前年
            int month = calendar.get(Calendar.MONTH) + 1; //当前月
            a = year + "-" + month + "-01 00:00:00";
            map.put("start", a);
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            b = simpleDateFormat.format(date);
            map.put("end", b);
        } else {
            a = start + " 00:00:00";
            b = end + " 23:59:59";
            map.put("start", a);
            map.put("end", b);
        }
        List<Map> list = orderService.queryShouRu(map);
        for (Map m : list) {
            int courseId= (int) m.get("courseId");
            Map map1=new HashMap();
            map1.put("start",a);
            map1.put("end",b);
            map1.put("courseId",courseId);
            int count=orderService.queryUserOrderCount(map1); //得到该门课程普通用户的购买次数并存入list
            m.put("countUser",count);
        }
        if (list.size()==0){
            List list1=new ArrayList();
            list1.add(0);
            return list1;
        }
        return list;
    }

    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }


    /**
     * 钱东升
     * @return
     */
    @RequestMapping("/getShowTeacher")
    @ResponseBody
    public List getShowTeacher(){
        return teacherService.getShowTeacher();
    }
}

